import 'package:flutter/material.dart';
import '../ScopedModels/ScopedMain.dart';
import 'package:scoped_model/scoped_model.dart';
import 'dart:typed_data';
import '../Common/api.dart';
import 'package:flutter_advanced_networkimage/flutter_advanced_networkimage.dart';

class AuthPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _AuthPageState();
  }
}

class _AuthPageState extends State<AuthPage> {
  GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  Uint8List _imageList = Uint8List(10);
  Map<String, dynamic> _formData = {
    'userName': null,
    'password': null,
    'isAgree': false,
    'vcode': null
  };

  Widget _buileNameText(ScopedMain model) {
    final valid = RegExp(
        r"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?");
    return TextField(
      keyboardType: TextInputType.emailAddress,
      decoration: InputDecoration(
          labelText: 'Email', fillColor: Colors.white, filled: true),
      onChanged: (String value) {
        setState(() {
          _formData['userName'] = value;
        });
      },
    );
  }

  Widget _buildPasswordText() {
    return TextField(
      obscureText: true,
      decoration: InputDecoration(
          labelText: '密码',
          counterText: '8~16位密码',
          filled: true,
          fillColor: Colors.white),
      onChanged: (String value) {
        setState(() {
          setState(() {
            _formData['password'] = value;
          });
        });
      },
    );
  }

  Widget _buildSwith() {
    return SwitchListTile(
      value: _formData['isAgree'],
      onChanged: (bool value) {
        setState(() {
          _formData['isAgree'] = value;
        });
      },
      title: Text('用户协议',
          style: TextStyle(
            color: Colors.black,
          )),
    );
  }

  void _login(ScopedMain model) {
    model.imageCode(_formData['userName']).then((byte) {
      setState(() {
        _imageList = byte;
      });
      showDialog(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              title: Text('登录验证'),
              content: Container(
                  child: Row(
                children: <Widget>[
                  Expanded(child: TextField(
                    onChanged: (String value) {
                      setState(() {
                        _formData['vcode'] = value;
                      });
                    },
                  )),
                  FlatButton(
                    child: Image.memory(_imageList),
                    onPressed: () {
                      model.imageCode(_formData['userName']).then((byte) {
                        setState(() {
                          _imageList = byte;
                          print(_imageList);
                        });
                      });
                    },
                  ),
                ],
              )),
              actions: <Widget>[
                FlatButton(
                  child: Text('取消'),
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                ),
                FlatButton(
                  child: Text('确定'),
                  onPressed: () {
                    model
                        .signUp(_formData['userName'], _formData['password'],
                            _formData['vcode'])
                        .then((flag) {
                      model.authToken(
                          _formData['userName'], _formData['password']);
                    });
                  },
                )
              ],
            );
          });
    });

    // Navigator.pushReplacementNamed(context, '/products');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('登录'),
      ),
      body: Container(
          decoration: BoxDecoration(
              image: DecorationImage(
            fit: BoxFit.cover,
            colorFilter: ColorFilter.mode(
                Colors.black.withOpacity(0.5), BlendMode.dstATop),
            image: AssetImage('assets/background.jpg'),
          )),
          margin: EdgeInsets.all(10.0),
          child: Center(
              child: SingleChildScrollView(
                  child: Form(
                      key: _formKey,
                      child: ScopedModelDescendant(builder:
                          (BuildContext context, Widget child,
                              ScopedMain model) {
                        return Column(
                          children: <Widget>[
                            _buileNameText(model),
                            _buildPasswordText(),
                            _buildSwith(),
                            SizedBox(height: 10.0),
                            FlatButton(
                              child: Image.memory(_imageList),
                              onPressed: () {
                                model
                                    .imageCode(_formData['userName'])
                                    .then((byte) {
                                  setState(() {
                                    _imageList = byte;
                                    print(_imageList);
                                  });
                                });
                              },
                            ),
                            RaisedButton(
                              color: Theme.of(context).primaryColor,
                              child: Text('login'),
                              textColor: Colors.white,
                              onPressed: () => _login(model),
                            ),
                          ],
                        );
                      }))))),
    );
  }
}
